package com.android.zmusic.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Audio.AudioColumns;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

import com.android.zmusic.adapter.GridViewAdapter;
import com.android.zmusic.adapter.ListViewAdapter;
import com.android.zmusic.interfaces.IOnSliderHandleViewClickListener;
import com.android.zmusic.musicplay.MenuItemData;
import com.android.zmusic.musicplay.MusicData;
import com.android.zmusic.musicplay.MusicPlayMode;
import com.android.zmusic.musicplay.MusicTimer;
import com.android.zmusic.service.ServiceManager;

public class ZMusicPlayActivity extends Activity {
    

	/** Called when the activity is first created. */
	//广播名称
	private final String BROCAST_NAME = "com.android.musicplay.brocast";
	
	//更新进度条
	private final static int REFRESH_PROGRESS_EVENT = 0;
	
	//关于dialog
	private final static int ABOUT_DIALOG_ID = 1;
	
	private Handler mHandler;
	
	private UIManager mUIManager;
	
	private ServiceManager mServiceManager;
	
	private MusicTimer mMusicTimer;
	
	//音乐播放状态广播
	private MusicPlayStateBrocast mplayStateBrocast;
	
	//SD卡状态广播
    private SDStateBrocast mSDStateBrocast;
	
    //音乐列表
    private List<MusicData> mMusicFileList;
    
    //listView适配
    private ListViewAdapter mListViewAdapter;
    
    //SD卡是否推出
    private boolean mIsSDExist = false;
    
    //是否含有数据
    private boolean mIsHaveDate = false;
    
    private int mCurMusicTotalTime = 0;
    
    //当前播放模式
    private int mCurPlayMode =MusicPlayMode.MP3_LIST_LOOP_PLAY;
   
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        init();
    }
    
    /**
     * 获取音乐列表
     * @return
     */
    public List<MusicData> getMusicFileList() {
    	
    	List<MusicData> list = new ArrayList<MusicData>();
        String[] projection = new String[]{BaseColumns._ID,
        								   MediaColumns.TITLE,
        								   AudioColumns.DURATION,
        								   MediaColumns.DATA,
        								   AudioColumns.ARTIST};
        Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
        if(null != cursor) {
        	cursor.moveToFirst();
        	
        	int nameIndex = cursor.getColumnIndex(MediaColumns.TITLE);
        	int timeIndex = cursor.getColumnIndex(AudioColumns.DURATION);
        	int pathIndex = cursor.getColumnIndex(MediaColumns.DATA);
        	int artistIndex = cursor.getColumnIndex(AudioColumns.ARTIST);
        	
        	int fileCount = cursor.getCount();
        	
        	for(int count = 0; count<fileCount; count ++) {
        		
        		MusicData data = new MusicData();
        		data.mMusicName = cursor.getString(nameIndex);
        		data.mMusicTime = cursor.getInt(timeIndex);
        		data.mMusicAritst = cursor.getString(artistIndex);
        		data.mMusicPath = cursor.getString(pathIndex);
        		
        		list.add(data);
        		cursor.moveToNext();
        	}
        	cursor.close();
        }
    	return list;
    }
    
    private void init() {
    	
    	mHandler  = new Handler(){
    		@Override
    		public void handleMessage(Message msg) {
    			// TODO Auto-generated method stub
    			switch (msg.what) {
				case REFRESH_PROGRESS_EVENT:  {//更新进度条
				
				    mUIManager.setPlayInfo(mServiceManager.getCurPosition(),mCurMusicTotalTime,null);
				}
					break;

				default:
					break;
				}
    		}
    	};
    	
    	mUIManager = new UIManager();
    	
    	mServiceManager = new ServiceManager(this);
    	mServiceManager.setOnServiceConnectComplete(this);
    	mServiceManager.connectService();
    	
    	mMusicTimer = new MusicTimer(mHandler,REFRESH_PROGRESS_EVENT);
    	
    	mMusicFileList = new ArrayList<MusicData>();
    	mListViewAdapter = new ListViewAdapter(this,mMusicFileList);
        mUIManager.mListView.setAdapter(mListViewAdapter);
		
		
    	//注册播放状态广播
    	mplayStateBrocast = new MusicPlayStateBrocast();
    	IntentFilter playFilter = new IntentFilter(BROCAST_NAME);
    	registerReceiver(mplayStateBrocast, playFilter);
    	
    	//注册SD卡状态广播
    	mSDStateBrocast  = new SDStateBrocast();
    	IntentFilter sdFilter = new IntentFilter();
    	sdFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    	sdFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    	sdFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
    	sdFilter.addAction(Intent.ACTION_MEDIA_EJECT);
    	sdFilter.addDataScheme("file");
    	registerReceiver(mSDStateBrocast, sdFilter);
	}
    
   public void showNoData() {
	   Toast.makeText(this, "No Music...", Toast.LENGTH_LONG).show();
   }

    
    //下一首
	public void playNext() {
		
	}
    
	//前一首
	public void playPre() {
		// TODO Auto-generated method stub
		
	}
	
    //停止
	public void stop() {
		// TODO Auto-generated method stub
		
	}
	
    //暂停
	public void pause() {
		// TODO Auto-generated method stub
		
	}
    
	//播放
	public void rePlay() {
		// TODO Auto-generated method stub
		
	}

    //播放模式
	public void modeChange() {
		// TODO Auto-generated method stub
		
	}
	
	//音量调节
	public void volunmChange() {
		
		Toast.makeText(ZMusicPlayActivity.this, "别摁了,这个按钮摆设用的", Toast.LENGTH_SHORT).show();					;
	}
    
    
	class UIManager implements OnItemClickListener {
		
		private View mMusicListView;
        private SliderDrawerManager mSliderDrawerManager;
        private PopMenuManager mPopMenuManager;
        private ListView mListView;
        
        //模式图片ID
        private int[] mModeDrawableIDs = {
        		R.drawable.mode_single_loop,
				R.drawable.mode_order,
        		R.drawable.mode_list_loop,
        		R.drawable.mode_random};
        private String[] mModeString = {
        		"单曲循环",
        		"顺序播放",
        		"列表循环",
        		"随机播放"
        		
        };

		public UIManager() {
			initView();
	    }
		
		private void initView() {
			
			mListView = (ListView) findViewById(R.id.listView);
			mListView.setOnItemClickListener(this);
			mMusicListView  = findViewById(R.id.listLayout);   //音乐列表listView
			
			mSliderDrawerManager  = new SliderDrawerManager();
			mPopMenuManager = new PopMenuManager();
		}
		
	   /**
	    * 当前播放信息
	    * @param curPosition
	    * @param mCurMusicTotalTime
	    * @param name
	    */
		public void setPlayInfo(Object curPosition, int mCurMusicTotalTime,
				String name) {
			// TODO Auto-generated method stub
			
		}
		
		
		//显示handle
		private void showHandlePanel(boolean b) {
			
			if(b) {
				
				mSliderDrawerManager.mBtnHandle.setVisibility(View.VISIBLE);
			}else {
				
//				mSliderDrawerManager.mBtnHandle.setVisibility(View.INVISIBLE);
			}
		}
		
	
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 音乐列表点击事件
			
		}


		
        class PopMenuManager implements OnDismissListener {
        	
        	private MenuItemData mMenuItemData;
        	private GridView mMenuGrid; 
        	private View mMenuView;
        	private GridViewAdapter mGridViewAdapter;
        	private PopupWindow mPopupWidow;
        	
        	private View mPopBackgroundView;

			public PopMenuManager() {
				
				initMenuView();
			}

			private void initMenuView() {
				mPopBackgroundView = findViewById(R.id.VirtualLayout);

				String[] menu_name_array = getResources().getStringArray(R.array.menu_item_name_array);
				LevelListDrawable mLevelListDrawable = (LevelListDrawable) getResources().getDrawable(R.drawable.menu_image_list);
				mMenuItemData = new MenuItemData(mLevelListDrawable, menu_name_array, menu_name_array.length);
				LayoutInflater inflater = getLayoutInflater();
				mMenuView = inflater.inflate(R.layout.menu, null);
				mMenuGrid = (GridView) mMenuView.findViewById(R.id.menuGridView);
				
				mGridViewAdapter = new GridViewAdapter(ZMusicPlayActivity.this,mMenuItemData);
				mMenuGrid.setAdapter(mGridViewAdapter);
				
				mPopupWidow = new PopupWindow(mMenuView,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				mPopupWidow.setFocusable(true);  //如果没有获得焦点，menu中的控件的事件无法响应
				
				ColorDrawable mcolor = new ColorDrawable(0x000);
				mPopupWidow.setBackgroundDrawable(mcolor);
				
				mPopupWidow.setAnimationStyle(android.R.style.Animation_Dialog);
				mPopupWidow.setOnDismissListener(this);
				
				
				
				mMenuGrid.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						onMenuItemClick(position);
					}
				});
				
				mMenuGrid.setOnKeyListener(new OnKeyListener() {
					
					@Override
					public boolean onKey(View v, int keyCode, KeyEvent event) {
						switch (keyCode) {
						case KeyEvent.KEYCODE_MENU:
							showMenuWindow();
							break;
						}
						return false;
					}
				});
			}
            
			/**
			 * 菜单按钮点击事件
			 */
			protected void onMenuItemClick(int position) {
				// TODO Auto-generated method stub
				
			}
        	
		    //显示菜单
		    public void showMenuWindow() {
		    	
		    	if(mPopupWidow.isShowing()) {
		    		mPopupWidow.dismiss();
		    		mPopBackgroundView.setVisibility(View.INVISIBLE);
		    	}else {
		    		mPopupWidow.showAsDropDown(findViewById(R.id.mainLayout),0,-125);
		    		mPopBackgroundView.setVisibility(View.VISIBLE);
		    	}
			}

			@Override
			public void onDismiss() {
				
				mPopBackgroundView.setVisibility(View.INVISIBLE);
			}
		    
        }


		class SliderDrawerManager implements OnClickListener, OnDrawerOpenListener, OnDrawerCloseListener ,
		                                     IOnSliderHandleViewClickListener, OnSeekBarChangeListener {
			
			private MySlidingDrawer mSlidingDrawer;   
			
			/**handle中的控件*/
			private ImageButton mBtnHandle;
			private ImageButton mBtnHandlePlay;        //handle上的播放按钮
			private ImageButton mBtnHandlePause;       //handle上的暂停按钮
			private TextView    mSongNumTextView;      //歌曲数量
			private View        mHandlePane;
			private TextView    mPlaySongTextView;     //当前播放的歌曲名
			
			/**content中的控件*/
			private ImageButton mBtnModeSet;           //播放模式
			private ImageButton mBtnVolumnSet;         //声音调节按钮
			private SeekBar     mPlayProgress;         //进度条
			private TextView    mCurTimeTextView;      //播放时间
			private TextView    mTotalTimeTextView;    //歌曲总时间
			
			private ImageButton mBtnPlay;              //播放按钮
			private ImageButton mBtnPause;             //暂停按钮
			private ImageButton mBtnStop;              //停止按钮
			private ImageButton mBtnPlayPre;           //上一首
			private ImageButton mBtnPlayNext;          //下一首
			private ImageButton mBtnMenu;              //菜单按钮
			
			private boolean mPlayAuto = true;

			private void initView() {

				mBtnHandle = (ImageButton) findViewById(R.id.handle_icon);
				mBtnHandlePlay 	= (ImageButton) findViewById(R.id.handle_play);
				mBtnHandlePause = (ImageButton) findViewById(R.id.handle_pause);
				mBtnModeSet = (ImageButton) findViewById(R.id.buttonMode);
				mBtnVolumnSet = (ImageButton) findViewById(R.id.buttonVolumn);
				mBtnPlay = (ImageButton) findViewById(R.id.buttonPlay);
				mBtnPause = (ImageButton) findViewById(R.id.buttonPause);
				mBtnStop = (ImageButton) findViewById(R.id.buttonStop);
				mBtnPlayPre = (ImageButton) findViewById(R.id.buttoPlayPre);
				mBtnPlayNext = (ImageButton) findViewById(R.id.buttonNext);
				mBtnMenu = (ImageButton) findViewById(R.id.buttonMenu);
				
				//按钮点击事情
				mBtnHandle.setOnClickListener( this);
				mBtnHandlePlay.setOnClickListener( this);
				mBtnHandlePause.setOnClickListener( this);
				mBtnModeSet.setOnClickListener( this);
				mBtnVolumnSet.setOnClickListener( this);
				mBtnPlay.setOnClickListener( this);
				mBtnPause.setOnClickListener( this);
				mBtnStop.setOnClickListener( this);
				mBtnPlayPre.setOnClickListener( this);
				mBtnPlayNext.setOnClickListener( this);
				mBtnMenu.setOnClickListener( this);			
				
				mSongNumTextView = (TextView) findViewById(R.id.textSongNum);
				mPlaySongTextView = (TextView) findViewById(R.id.textPlaySong);
				mCurTimeTextView = (TextView) findViewById(R.id.textViewCurTime);
				mTotalTimeTextView = (TextView) findViewById(R.id.textViewTotalTime);
				
				mSlidingDrawer = (MySlidingDrawer) findViewById(R.id.slidingdrawer);
				mSlidingDrawer.setOnDrawerOpenListener(this);
				mSlidingDrawer.setOnDrawerCloseListener(this);
				mSlidingDrawer.setMhandleId(R.id.handle_icon);
				mSlidingDrawer.setmTouchableIds(new int[]{R.id.handle_play,R.id.handle_pause});
				mSlidingDrawer.setmTouchViewClickListener(this);
				
				mHandlePane = findViewById(R.id.handle_panel);
				
				mPlayProgress = (SeekBar) findViewById(R.id.seekBar);
				mPlayProgress.setOnSeekBarChangeListener(this);
			} 
			
			public SliderDrawerManager() {
				initView();
			}
			
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.buttonPlay:
					rePlay();
					break;
				case R.id.buttonPause:
					pause();
					break;
				case R.id.buttonStop:
					stop();
					break;
				case R.id.buttoPlayPre:
					playPre();
					break;
				case R.id.buttonNext:
					playNext();
					break;
				case R.id.buttonMenu:
					showMenuWindow();
					break;
				case R.id.buttonMode:
					modeChange();
					break;
				case R.id.buttonVolumn:
					volunmChange();
					break;				
				}
				
			}
			

			
			@Override
			public void onDrawerOpened() {
				mMusicListView.setVisibility(View.INVISIBLE);
				mBtnHandle.setImageResource(R.drawable.handle_down);
//				showHandlePanel(false);
			}
		
			@Override
			public void onDrawerClosed() {
				
				mMusicListView.setVisibility(View.VISIBLE);
				mBtnHandle.setImageResource(R.drawable.handle_up);
//				showHandlePanel(true);
			}
			
			@Override
			public void onViewClick(View view) {

				switch (view.getId()) {
				case R.id.handle_play:
					rePlay();
					break;
				case R.id.handle_pause:
					pause();
					break;
				}
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if(mPlayAuto) {
					mServiceManager.seekTo(progress);
				}
				
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
				mPlayAuto  = false;
				
			}
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				
				mPlayAuto = true;
			}
			
			
		}

        /**
         * 显示菜单
         */
		public void showMenuWindow() {
			
			mPopMenuManager.showMenuWindow();
		}
	
    }
    
    /**
	 * 接收音乐播放状态改变（暂停，播放，准备就绪等）
	 * @author administrator
	 */
    class MusicPlayStateBrocast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			
		}
    	
    }
    
    
    /**
     * 接收SD卡状态改变广播
     * @author administrator
     *
     */
   class SDStateBrocast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

		}

	}
}